#include "timer.h" 
#include "servo.h"
#include "motor.h"
#include "led.h" 
#include "Justin_Beeper.h"
#include "M2M_Serial_Console.h"
#include "M2P_Serial_Console.h"
//通用定时器 3中断初始化
//这里时钟选择为 APB1的 2倍，而 APB1为 36M //arr：自动重装值。
//psc：时钟预分频数
//这里使用的是定时器 3! 

u16 System_Time_Counter=0;

void Timer_init(u16 arr,u16 psc) 
{ 
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; 
    NVIC_InitTypeDef NVIC_InitStructure; 
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //①时钟 TIM4使能
    //定时器 TIM4初始化
    TIM_TimeBaseStructure.TIM_Period = arr; //设置自动重装载寄存器周期的值
    TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置时钟频率除数的预分频值
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数
    TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //②初始化 TIM3
    TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE ); //③允许更新中断
    //中断优先级 NVIC设置
    NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn; //TIM3中断
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //先占优先级 0级
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //从优先级 3级
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
    NVIC_Init(&NVIC_InitStructure); //④初始化 NVIC寄存器
    TIM_Cmd(TIM4, ENABLE); //⑤使能 TIM4
}

 //定时器 3中断服务程序⑥
void TIM4_IRQHandler(void) //TIM3中断
{ 
    if (TIM_GetITStatus(TIM4, TIM_IT_Update) != RESET) //检查 TIM3更新中断发生与否
    { 
        TIM_ClearITPendingBit(TIM4, TIM_IT_Update ); //清除 TIM3更新中断标志
        System_Time_Counter++;
        Timer_EventCheck();
        if(System_Time_Counter>=System_Routine)
        {
            System_Time_Counter=0;
            
        }
    } 
}

void Timer_EventCheck(void)
{
    if(M2MSerial_RxWaiting)
        M2MSerial_RxWaitingTim++;
    if(System_Time_Counter%Servo_AdjustRoutine==0)
        Flag_ServoAdjust=1;
    if(System_Time_Counter%Beeper_UnitTime_ms==0)
        Beeper_SwitchCounter++;
    if(System_Time_Counter%RevolverMotor_SpeedRoutine==0)
        Flag_SpeedAdjust=1;
    if(System_Time_Counter%LALMotor_AdjustInterval==0)
    {
        Flag_LALMotorAdjust=1;
    }
    if(System_Time_Counter%(M2PSerial_TxRoutine_10ms*10)==0)
    {
        Flag_M2PSend=1; 
    }
        
}

